package com.yl.auth.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yl.auth.entity.User;
import com.yl.auth.entity.Jigouzhongxinduanaccount;
import com.yl.auth.service.JigouzhongxinduanaccountService;
import com.yl.auth.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 王庆梁
 * @datetime 2023/6/8 17:27
 * @description 类对象
 */
@Component
public class TokenUtils {

    private static UserService staticSysUserService;

    private static JigouzhongxinduanaccountService jigouzhongxinduanaccountService;

    @Resource
    private UserService sysUserService;

    @Resource
    private JigouzhongxinduanaccountService jigouzhongxinduanaccount;

    @PostConstruct
    public void setUserService() {
        staticSysUserService = sysUserService;
    }

    @PostConstruct
    public void setJiGouService(){
        jigouzhongxinduanaccountService = jigouzhongxinduanaccount;
    }

    /**
     * 生成token
     */
    public static String getToken(String userId, String sign) {
        return JWT.create().withAudience(userId)  //将user id保存到token里面 ,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))  //2小时后token过期
                .sign(Algorithm.HMAC256(sign)); //以password作为token的密钥
    }

    /**
     * 获取当前登录的用户信息
     * 如果在静态方法中 必须要调用静态的对象
     * @return
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticSysUserService.getById(Integer.valueOf(userId));
            }
        }catch (Exception e) {
            return null;
        }
        return null;
    }
    /**
     * 获取当前登录的用户信息
     * 如果在静态方法中 必须要调用静态的对象
     * @return
     */
    public static Jigouzhongxinduanaccount getCurrentJiGou() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return jigouzhongxinduanaccountService.getById(Integer.valueOf(userId));
            }
        }catch (Exception e) {
            return null;
        }
        return null;
    }
}
